14 / 19

Why are Strings immutable in Java/C#? What are the benefits?

String Immutability

  1. 1

    String interning and pooling become safe because shared strings cannot be changed by one consumer.

  2. 2

    Immutability makes strings easier to reason about in concurrent programs.

  3. 3

    Hash codes can be safely cached because the contents cannot change.

  4. 4

    Strings used as map keys remain stable after insertion.

  5. 5

    Immutability reduces certain classes of accidental state-sharing bugs.

  6. 6

    Repeated concatenation can still be inefficient, so StringBuilder or equivalent builders should be used for many modifications.

Difficulty: 3/10

Follow-up Questions

  • How does string interning work?
  • Why is StringBuilder more efficient for repeated concatenation?